package it.codelair.bakekaservice.Utilities;

import it.codelair.bakekaservice.bean.Ente;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;

import org.json.JSONObject;

public class EntiManager {
	
	public static ArrayList<Ente> getEnti(){
		try {
			URL url = new URL("http://www.bakekaservice.it/nuovo/getEnti.php");

			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);

			BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
			out.flush();
			out.close();
			BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );

			String response;
			JSONObject json=null;
			while ( (response = in.readLine()) != null ) {
				json = new JSONObject(response);
			}
			in.close();
			ArrayList<String> lista = new ArrayList<String>();
			Iterator it = json.keys();
			while(it.hasNext()){
				lista.add(""+it.next());
			}
			ArrayList<Ente> enti = new ArrayList<Ente>();
			for(int i=0;i<lista.size();i++){
				JSONObject array = json.getJSONObject(lista.get(i));
				Ente ent = new Ente();
				ent.setIdCompany(Utilities.convertHexToString(array.getString("A1")));
				ent.setSipAddress(Utilities.convertHexToString(array.getString("A2")));
				ent.setBusinessName(Utilities.convertHexToString(array.getString("A3")));
				ent.setLogo(Utilities.convertHexToString(array.getString("A4")));
				ent.setAddress(Utilities.convertHexToString(array.getString("A5")));
				ent.setCity(Utilities.convertHexToString(array.getString("A6")));
				ent.setProvince(Utilities.convertHexToString(array.getString("A7")));
				ent.setClosedDay(Utilities.convertHexToString(array.getString("A8")));
				ent.setPoints(Utilities.convertHexToString(array.getString("A9")));
				ent.setDiscount(Utilities.convertHexToString(array.getString("A10")));
				ent.setExtra(Utilities.convertHexToString(array.getString("A11")));
				ent.setSite(Utilities.convertHexToString(array.getString("A12")));
				ent.setMap(Utilities.convertHexToString(array.getString("A13")));
				ent.setCategory(Utilities.convertHexToString(array.getString("A14")));
				enti.add(ent);
			}
			return enti;
		}
		catch ( MalformedURLException ex ) {
			ex.printStackTrace();
			return null;
		}
		catch ( IOException ex ) {
			ex.printStackTrace();
			return null;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
